# -*- coding:utf-8 -*-

from win32event import CreateMutex
from win32api import CloseHandle, GetLastError
from winerror import ERROR_ALREADY_EXISTS


class Singleinstance(object):
    """将应用程序限制为单实例运行
    https://www.programcreek.com/python/example/98746/win32event.CreateMutex
    """

    def __init__(self):
        self.mutexname = "WXR_{D0E858DF-985E-4907-B7FB-8D732C3FC3B8}"
        self.mutex = CreateMutex(None, False, self.mutexname)
        self.lasterror = GetLastError()

    def aleradyrunning(self):
        return (self.lasterror == ERROR_ALREADY_EXISTS)

    def __del__(self):
        if self.mutex:
            CloseHandle(self.mutex)


def _test():
    app = Singleinstance()
    if app.aleradyrunning():
        from sys import exit
        print "Another instance of this program is already running"
        exit(0)
    print 'ok'


if __name__ == "__main__":
    _test()
    input('123456')
